package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;

import common.ServerResponse;
import domain.user;
import service.IUserService;
import service.impl.UserServiceImpl;
import util.jdbcUtil;

@WebServlet("/user")
public class UserServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		setHead(request,response);
		System.out.println("进入servlet");
		String type=request.getParameter("type");
		System.out.println("type:"+type);
		if("login".equals(type)) {
			//登录，获取用户名密码
			login(request,response);
		}else if("register".equals(type)) {
			//注册
			register(request,response);
		}else if("check_valid".equals(type)) {
			//检查用户名是否有效
			check_valid(request,response);
		}else if("get_user_info".equals(type)) {
			//获取登录用户信息
			get_user_info(request,response);
		}
		else if("forget_get_question".equals(type)) {
			forget(request,response);
		}
		else if("forget_check_answer".equals(type)) {
			submit(request,response);
		}
		else if("forget_reset_password".equals(type)) {
			forgetReset(request,response);
		}
		else if("reset_password".equals(type)) {
			reset(request,response);
		}
		else if("update_information".equals(type)) {
			update_information(request,response);
		}
		else if("get_information".equals(type)) {
			get_information(request,response);
		}
		else if("logout".equals(type)) {
			logout(request,response);
		}
		else if("is_login".equals(type)) {
			is_login(request,response);
		}
		else if("list".equals(type)) {
			list(request,response);
		}
	
	
	
	}
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	protected void setHead(HttpServletRequest request, HttpServletResponse response) {
		//转发时候防止中文乱码
	    response.setHeader("content-type", "text/html;charset=UTF-8");
	    response.setCharacterEncoding("UTF-8");
	    String originHeader=request.getHeader("Origin");
		/* 允许跨域的主机地址 */ response.setHeader("Access-Control-Allow-Origin", originHeader);
		/* 允许跨域的请求方法GET, POST, HEAD 等 */ response.setHeader("Access-Control-Allow-Methods", "*"); 
		/* 重新预检验跨域的缓存时间 (s) */ response.setHeader("Access-Control-Max-Age", "3600");
		/* 允许跨域的请求头 */ response.setHeader("Access-Control-Allow-Headers", "*"); 
		/* 是否携带cookie */ response.setHeader("Access-Control-Allow-Credentials", "true");
	}
	
	
	
	//具体的servlet操作区//
	
	//更改个人信息
	protected void update_information(HttpServletRequest request, HttpServletResponse response) {
		
		//HttpSession
        HttpSession session = request.getSession();
        //session.setAttribute("id", id);
		Object id = session.getAttribute("id");
        //String id="1";
		String email=request.getParameter("email");
		String phone=request.getParameter("phone");
		String question=request.getParameter("question");
		String answer=request.getParameter("answer");
		IUserService u=new UserServiceImpl();
		ServerResponse se = u.Update_information(id,email, phone, question, answer);
		getjson(se,response);
	}
	
	//显示个人所有信息
	protected void get_information(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("进入");
		//HttpSession
        HttpSession session = request.getSession();
        //session.setAttribute("id", id);
		Object Id = session.getAttribute("id");
		String id=Id.toString();
		System.out.println("当前登录的用户的id为"+id);
        //String id="1";
		IUserService u=new UserServiceImpl();
		ServerResponse se = u.Get_information(id);
		getjson(se,response);
	}
	//退出登录
	protected void logout(HttpServletRequest request, HttpServletResponse response) {
		
		HttpSession session=request.getSession();
		//session.setAttribute("id",null);//双重保障
		session.invalidate();
		ServerResponse se=ServerResponse.serverResponseBySuccess("退出成功！！！");
		getjson(se,response);
	}
	
	//登录
		protected void login(HttpServletRequest request, HttpServletResponse response) {
				String username = request.getParameter("username");
				String password = request.getParameter("password");
				
				//执行登录逻辑
				IUserService userService = new UserServiceImpl();
				ServerResponse se = userService.loginLogic(username, password);
				
				//将id,role放入session
				user USER = (user)se.getData();
				if(USER!=null) {
					Long id = USER.getId();
					Long role = USER.getRole();
					HttpSession session = request.getSession();
			        session.setAttribute("id",id );
			        session.setAttribute("role", role);
				} 
				//将ServerResponse转为json并通过流写出
				getjson(se,response);
			}	
		//注册
	protected void register(HttpServletRequest request, HttpServletResponse response) {
		
			// TODO Auto-generated method stub
			String username=request.getParameter("username");
			String password=request.getParameter("password");
			String email=request.getParameter("email");
			String phone=request.getParameter("phone");
			String question=request.getParameter("question");
			String answer=request.getParameter("answer");
			//执行注册逻辑
			IUserService userService = new UserServiceImpl();
			ServerResponse se = userService.registerLogic(username,password,email,phone,question,answer);
			//将ServerResponse转为json并通过流写出
			getjson(se,response);
		}
		//检查用户名是否有效
	protected void check_valid(HttpServletRequest request, HttpServletResponse response) {
		
			// TODO Auto-generated method stub
			String username = request.getParameter("username");
			String email = request.getParameter("email");
			String box_type = request.getParameter("box_type");
			String str = "";
			if(box_type.equals("username")) {
				str=username;
			}else {
				str=email;
			}
			//执行检查逻辑
			IUserService userService = new UserServiceImpl();
			ServerResponse se = userService.check_valid(str, box_type);
			//将ServerResponse转为json并通过流写出
			getjson(se,response);
		}
		//获取登录用户信息
	protected void get_user_info(HttpServletRequest request, HttpServletResponse response) {
		
			// TODO Auto-generated method stub
			//获取session中储存的id
			HttpSession session = request.getSession();
			Object Obj_id = session.getAttribute("id");
			String id = Obj_id.toString();
		    //String id="1";
			//执行获取逻辑
			IUserService userService = new UserServiceImpl();
			ServerResponse se = userService.get_user_info(id);
			//将ServerResponse转为json并通过流写出
			getjson(se,response);
		}
	
	//忘记密码
		protected void forget(HttpServletRequest request, HttpServletResponse response) {
			
			// TODO Auto-generated method stub
			
			String username=request.getParameter("username");
			IUserService u=new UserServiceImpl();
			ServerResponse se = u.forget(username);
			getjson(se,response);
			
			
			
		}
		//提交问题
		protected  void submit(HttpServletRequest request, HttpServletResponse response) {
			
			// TODO Auto-generated method stub
			//验证答案
			String answer=request.getParameter("answer");
			String username=request.getParameter("username");
			IUserService u=new UserServiceImpl();
			ServerResponse se = u.submit(answer,username);
			getjson(se,response);
			
			//正确：   错误：   
			
		}
		//忘记密码中重设密码
		protected  void forgetReset(HttpServletRequest request, HttpServletResponse response) {
			
			// TODO Auto-generated method stub
			//输入新密码
			String username=request.getParameter("username");
			String passwordNew=request.getParameter("passwordNew");
			System.out.println("此时的password"+passwordNew);
			IUserService u=new UserServiceImpl();
			ServerResponse se = u.forgetReset(username,passwordNew);
			getjson(se,response);
			//验证新密码
			//一致：   不一致：   
			
		}
		//登录状态中重设密码
		protected  void reset(HttpServletRequest request, HttpServletResponse response) {
		         System.out.println("进入密码重置");
				// TODO Auto-generated method stub
				HttpSession session = request.getSession();
				String id=session.getAttribute("id").toString();
				if(id==null)
				{
					ServerResponse se =ServerResponse.serverResponseByError("用户未登录");
					getjson(se,response);
				}
				else {
						
					//输入新密码
					String newpw=request.getParameter("passwordNew");
					String passwordOld=request.getParameter("passwordOld");
					System.out.println("newma"+newpw);
					IUserService u2=new UserServiceImpl();
					ServerResponse se2 = u2.reset(id,passwordOld, newpw);
					getjson(se2,response);
					//验证新密码
					//一致：   不一致：
				}
		}
		
		protected void is_login(HttpServletRequest request, HttpServletResponse response) {
			//从session中获取登录用户的id
			HttpSession session = request.getSession();
			Object Obj_id = session.getAttribute("id");
			ServerResponse se=null;
			if(Obj_id==null) {
				se=ServerResponse.serverResponseByError("用户没有登录");
			}else {
				String id = Obj_id.toString();		
				//执行判断是否登录逻辑
				IUserService userService = new UserServiceImpl();
				se = userService.is_login(id);
				//将ServerResponse转为json并通过流写出
			}
			getjson(se,response);
			
		}
	protected void list(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("进入list");
		//pageSize  pageNum
		String pageSize=request.getParameter("pageSize");
		String pageNum=request.getParameter("pageNum");
		System.out.println("数据为："+pageSize+" "+pageNum);
		IUserService u = new UserServiceImpl();
		getjson(u.List(pageSize,pageNum),response);
		
	}
		
	
	
	protected void getjson(ServerResponse se,HttpServletResponse response) {
		Gson gson=new Gson();
		String json=gson.toJson(se);
		PrintWriter pw;
		try {
			pw=response.getWriter();
			pw.write(json);
			pw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
}